package com.l.im.common.auth;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.time.Instant;
import java.util.Date;

/**
 * @program: LIM
 * @description: jwt工具类
 * @author: Alex Wu
 * @createDate: 2025-04-15 09:56
 **/
public class JwtSecret {
    private static final String SECRET = "your-very-secure-secret";
    private static final long EXPIRATION = 5 * 60 * 1000; // 5分钟

    public static String generateToken(String appId, String jti, Instant issuedAt, Instant expiration) {
        // 使用安全的密钥生成方法，保证密钥长度符合要求
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

        return Jwts.builder()
                .setId(jti)
                .setSubject(appId)
                .setIssuedAt(Date.from(issuedAt))
                .setExpiration(Date.from(expiration))
                .signWith(key) // 使用自动生成的密钥
                .compact();
    }

    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8)))
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public static String getAppId(String token) {
        return parseToken(token).getSubject();
    }

    public static String getJti(String token) {
        return parseToken(token).getId();
    }

    public static boolean isTokenExpired(String token) {
        try {
            Date exp = parseToken(token).getExpiration();
            return exp.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }
}
